package com.rongxue.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.rongxue.pojo.ObjectResult;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HttpClientUtil {

	public ObjectResult sendPost(String url, String xml){
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;

		client = HttpClients.createDefault();
		URI uri = null;
		try {
			uri = new URI(url);
		} catch (URIException e) {
			e.printStackTrace();
		}
		HttpPost post = new HttpPost(String.valueOf(uri));
		List<BasicNameValuePair> formList = new ArrayList<>();

		formList.add(new BasicNameValuePair("FM", xml));
		StringEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(formList, "utf-8");

			post.setEntity(entity);

			//设置请求的报文头部的编码
			post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

			//设置期望服务端返回的编码
			post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

			//执行post请求
			response = client.execute(post);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200){
			return ObjectResult.build("0","服务器异常0x02,请稍后重试");
			}

			String resStr = EntityUtils.toString(response.getEntity());

			return ObjectResult.build("1", resStr);
			} catch (Exception e) {
				e.printStackTrace();
				return ObjectResult.build("0", "服务器异常0x02,请稍后重试");
			}finally {
				try {
					response.close();
					client.close();
				}catch (IOException e) {
					e.printStackTrace();
				}

		}
	}





	public ObjectResult request(String url, String content) {
		Map<String, Object> result = new HashMap<String, Object>();
		String errorStr = "";
		String status = "";
		String response = "";
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
			// 设置请求属性
			httpUrlConnection.setRequestProperty("Content-Type", "application/json");
			httpUrlConnection.setRequestProperty("x-adviewrtb-version", "2.1");
			// 发送POST请求必须设置如下两行
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(httpUrlConnection.getOutputStream());
			// 发送请求参数
			out.write(content);
			// flush输出流的缓冲
			out.flush();
			httpUrlConnection.connect();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				response += line;
			}
			status = new Integer(httpUrlConnection.getResponseCode()).toString();
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			errorStr = e.getMessage();
			return ObjectResult.build("0","发送 POST 请求出现异常");
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) { out.close();}
				if (in != null) {in.close();}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		result.put("errorStr", errorStr);
		result.put("response", response);
		result.put("status", status);
		return ObjectResult.build("1",response);
	}



	public static ObjectResult verificationOfBankCard(String url, Map<String, String> map){
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;

		client = HttpClients.createDefault();
		URI uri = null;
		try {
			uri = new URI(url);
		} catch (URIException e) {
			e.printStackTrace();
		}
		HttpPost post = new HttpPost(String.valueOf(uri));
		List<BasicNameValuePair> formList = new ArrayList<>();

		Set set2 = map.entrySet();
		for(Iterator iter = set2.iterator(); iter.hasNext();){
			Map.Entry entry = (Map.Entry)iter.next();
			formList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
		}

		StringEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(formList, "utf-8");

			post.setEntity(entity);

			//设置请求的报文头部的编码
			post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

			//设置期望服务端返回的编码
			post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

			//执行post请求
			response = client.execute(post);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200){
				ExceptionUtils.recordException(true, "聚合请求失败", statusCode+"", null);
				return ObjectResult.build("0","服务器异常0x02,请稍后重试");
			}

			String resStr = EntityUtils.toString(response.getEntity());
			System.out.println("======接收的json======"+resStr);

			Map<String,String> stringStringMap = (Map<String,String>) JSON.parse(resStr);
			System.out.println("======转换的map======"+stringStringMap);

			return ObjectResult.build("1", "", stringStringMap);
		} catch (Exception e) {

			ExceptionUtils.recordException(true, "聚合请求异常", "", e);
			return ObjectResult.build("0", "服务器异常0x02,请稍后重试");
		}finally {
			try {
				response.close();
				client.close();
			}catch (IOException e) {
				e.printStackTrace();
			}

		}
	}


}
